package com.dexgdx.game;

import java.util.Timer;
import java.util.TimerTask;

import com.dexgdx.game.action.MoveAction;
import com.dexgdx.game.actor.AbstractActor;
import com.dexgdx.game.initializer.DefaultConstants;
import com.dexgdx.game.manager.ActionData;
import com.dexgdx.game.manager.ActionManager;
import com.dexgdx.game.manager.ActorData;
import com.dexgdx.game.manager.ActorManager;
import com.dexgdx.game.structure.Region;
import com.dexgdx.game.structure.SelectionRectangle;

public class Game {
	
	private static boolean isInitialized;
	
	public static DefaultConstants defaultConstants;
	public static ActorData actorData;
	public static ActionData actionData;
	
	public static SelectionRectangle selectionRectangle;
	public static long renderTimer;
	
	public static void initialize(){
		if(!isInitialized){
			loadDefaultConstants();
			loadGameData();
			isInitialized = true;
		}
	}
	
	public static void run(){
		startTimer();
	}
	
	private static void loadDefaultConstants(){
		// TODO
		defaultConstants = new DefaultConstants(200, 150);
		selectionRectangle = new SelectionRectangle();
	}
	
	private static void loadGameData(){
		actorData = new ActorData();
		actionData = new ActionData();
		
		ActorManager.loadActorsFromJSON();
		
		renderTimer = System.currentTimeMillis();
	}
	
	private static void startTimer(){
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				ActionManager.runNextInQueue();
			}
		}, 10, 10);
		
	}
	
	
	
	public static void emptyScreenTouched(int x, int y){
		if(ActorManager.isAnyPlayerSelected()){
			for(Long playerIndex : actorData.getSelectedPlayerList()){
				AbstractActor actor = ActorManager.getActor(playerIndex);
				Region target = Region.fromXYAndRegion(x, y, actor);
				if(actor.getActorStatus().isMoving()){
					ActionManager.addMovingActorTarget(actor, target);
				}
				else {
					ActionManager.addToQueue(new MoveAction(actor, target));
				}
				x += actor.width + 10;
			}
		}
	}
}
